package com.ksyun.campus.metaserver.controller;

import com.ksyun.campus.metaserver.domain.DataServerInfo;
import com.ksyun.campus.metaserver.domain.dto.ApiResponse;
import com.ksyun.campus.metaserver.zk.ZooKeeperService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DataServer管理控制器
 * 提供DataServer注册数据的管理和修复功能
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/admin/dataserver-mgmt")
public class DataServerManagementController {
    
    @Autowired
    private ZooKeeperService zooKeeperService;
    
    /**
     * 清理所有DataServer注册数据
     */
    @PostMapping("/cleanup-all")
    public ApiResponse<Map<String, Object>> cleanupAllDataServers() {
        try {
            log.info("Starting cleanup of all DataServer registration data");
            
            // 获取清理前的状态
            List<DataServerInfo> beforeCleanup = zooKeeperService.getCurrentDataServers();
            int beforeCount = beforeCleanup.size();
            
            // 执行清理
            Map<String, Object> cleanupResult = zooKeeperService.cleanupAllDataServerRegistrations();
            
            if (!(Boolean) cleanupResult.get("success")) {
                return ApiResponse.error("Cleanup failed: " + cleanupResult.get("error"));
            }
            
            // 等待一段时间让缓存刷新
            Thread.sleep(2000);
            
            // 获取清理后的状态
            List<DataServerInfo> afterCleanup = zooKeeperService.getCurrentDataServers();
            int afterCount = afterCleanup.size();
            
            Map<String, Object> result = new HashMap<>();
            result.put("beforeCount", beforeCount);
            result.put("afterCount", afterCount);
            result.put("removedCount", (Integer) cleanupResult.get("removedCount"));
            result.put("message", cleanupResult.get("message"));
            
            log.info("Cleanup completed: removed {} invalid entries", beforeCount - afterCount);
            
            return ApiResponse.success(result);
            
        } catch (Exception e) {
            log.error("Error during DataServer cleanup", e);
            return ApiResponse.error("Failed to cleanup DataServer data: " + e.getMessage());
        }
    }
    
    /**
     * 列出ZooKeeper中的原始DataServer数据
     */
    @GetMapping("/raw-data")
    public ApiResponse<Map<String, Object>> getRawDataServerData() {
        try {
            Map<String, Object> rawDataResult = zooKeeperService.getRawDataServerData();
            
            if (!(Boolean) rawDataResult.get("success")) {
                return ApiResponse.error("Failed to get raw data: " + rawDataResult.get("error"));
            }
            
            return ApiResponse.success(rawDataResult);
            
        } catch (Exception e) {
            log.error("Error getting raw DataServer data", e);
            return ApiResponse.error("Failed to get raw data: " + e.getMessage());
        }
    }
    
    /**
     * 强制重新加载DataServer信息
     */
    @PostMapping("/force-reload")
    public ApiResponse<Map<String, Object>> forceReloadDataServers() {
        try {
            log.info("Force reloading DataServer information");
            
            // 获取重新加载前的状态
            List<DataServerInfo> beforeReload = zooKeeperService.getCurrentDataServers();
            
            // 这里可以添加强制重新加载的逻辑
            // 例如：重启DataServer缓存、重新连接ZooKeeper等
            
            // 等待一段时间让系统稳定
            Thread.sleep(2000);
            
            // 获取重新加载后的状态
            List<DataServerInfo> afterReload = zooKeeperService.getCurrentDataServers();
            
            Map<String, Object> result = new HashMap<>();
            result.put("beforeCount", beforeReload.size());
            result.put("afterCount", afterReload.size());
            result.put("healthyCount", afterReload.stream()
                    .filter(ds -> ds.isHealthy(30))
                    .count());
            result.put("message", "DataServer information reloaded successfully");
            
            return ApiResponse.success(result);
            
        } catch (Exception e) {
            log.error("Error during force reload", e);
            return ApiResponse.error("Failed to force reload: " + e.getMessage());
        }
    }
    
    /**
     * 检查DataServer注册状态
     */
    @GetMapping("/registration-status")
    public ApiResponse<Map<String, Object>> getRegistrationStatus() {
        try {
            List<DataServerInfo> dataServers = zooKeeperService.getCurrentDataServers();
            
            Map<String, Object> status = new HashMap<>();
            status.put("totalRegistered", dataServers.size());
            status.put("healthyNodes", dataServers.stream()
                    .filter(ds -> ds.isHealthy(30))
                    .count());
            status.put("activeNodes", dataServers.stream()
                    .filter(ds -> ds.getStatus() == DataServerInfo.DataServerStatus.ACTIVE)
                    .count());
            
            // 检查是否有足够的节点进行三副本
            boolean canAllocateReplicas = dataServers.size() >= 3;
            boolean hasHealthyReplicas = dataServers.stream()
                    .filter(ds -> ds.isHealthy(30))
                    .count() >= 3;
            
            status.put("canAllocateReplicas", canAllocateReplicas);
            status.put("hasHealthyReplicas", hasHealthyReplicas);
            
            if (!canAllocateReplicas) {
                status.put("warning", "Insufficient DataServers for 3-replica allocation");
            } else if (!hasHealthyReplicas) {
                status.put("warning", "Insufficient healthy DataServers for 3-replica allocation");
            } else {
                status.put("status", "Ready for 3-replica allocation");
            }
            
            return ApiResponse.success(status);
            
        } catch (Exception e) {
            log.error("Error getting registration status", e);
            return ApiResponse.error("Failed to get registration status: " + e.getMessage());
        }
    }
}
